import openpyxl
import os
import re


demo = r"E:\毕设数据\QuNDVI_Excel\新洲区\Excel_2020\2020_08_12_MOD13Q1_A2020225_h27v05_006_2020241233129_xinzhouqu.xlsx"


class Handle(object):
    """提取Excel中的最大值，最小值，平均值，并提供每个值的出现频率"""

    def __init__(self, filename):
        __workbook = openpyxl.load_workbook(filename, )
        self.__sheet = __workbook.active
        self.__max = self.__sheet[2][2].value
        self.__min = self.__sheet[2][3].value
        self.__mean = self.__sheet[2][4].value

    @property
    def max(self):
        return self.__max

    @property
    def min(self):
        return self.__min

    @property
    def avg(self):
        return self.__mean

    def count(self, value):
        """:return the given value's count"""
        __data = list(self.__sheet['A'])
        __count = list(self.__sheet['B'])
        __data.pop(0)
        __count.pop(0)
        __counts = [c.value for c in __count]
        __values = [x.value for x in __data]
        __dict = dict(zip(__values, __counts))
        if __dict.get(value):
            return __dict.get(value)
        else:
            return 0

    def test(self):
        print(self.__mean)
        print(self.__max)
        print(self.__min)
        # print(self.count(-0.1993))


class YearData(object):
    """
    以一个包含全年数据Excel表的文件夹为输入，可通过相应的方法求得最大值，最小值，平均值
    以及生长季平均值，月度最大值中的最小值，月度最小值中的最大值
    """

    def __init__(self, year_dir):
        self.__year = year_dir

    def __create_handles(self):
        files = []
        handles = []
        for i in os.listdir(self.__year):
            if i.endswith(".xlsx"):
                files.append(os.path.join(self.__year, i))

        for f in files:
            handles.append(Handle(f))
        return handles

    def year_avg(self):
        """返回一年的平均值"""
        handles = self.__create_handles()
        avg = sum([x.avg for x in handles]) / len(handles)
        return avg

    def growth_time_avg(self):
        files = []
        handles = []
        for i in os.listdir(self.__year):
            # print(int(re.search("\d{4}_(\d{2})_\d{2}", i).group(1)))
            if i.endswith(".xlsx") and 3 < int(re.search("\d{4}_(\d{2})_\d{2}", i).group(1)) < 11:
                files.append(os.path.join(self.__year, i))
        for f in files:
            handles.append(Handle(f))
        if len(handles) < 1:
            return None
        else:
            avg = sum([x.avg for x in handles]) / len(handles)
            return avg
    
    def growth_time_max(self):
        files = []
        handles = []
        for i in os.listdir(self.__year):
            # print(int(re.search("\d{4}_(\d{2})_\d{2}", i).group(1)))
            if i.endswith(".xlsx") and 3 < int(re.search("\d{4}_(\d{2})_\d{2}", i).group(1)) < 11:
                files.append(os.path.join(self.__year, i))
        for f in files:
            handles.append(Handle(f))
        if len(handles) < 1:
            return None
        else:
            max__ = max([x.max for x in handles])
            return max__
    
    def growth_time_min(self):
        files = []
        handles = []
        for i in os.listdir(self.__year):
            # print(int(re.search("\d{4}_(\d{2})_\d{2}", i).group(1)))
            if i.endswith(".xlsx") and 3 < int(re.search("\d{4}_(\d{2})_\d{2}", i).group(1)) < 11:
                files.append(os.path.join(self.__year, i))
        for f in files:
            handles.append(Handle(f))
        if len(handles) < 1:
            return None
        else:
            min__ = min([x.min for x in handles])
            return min__

    def year_max(self):
        """返回一年中的最大值"""
        return max([x.max for x in self.__create_handles()])

    def year_min(self):
        """返回一年中的最小值"""
        return min([x.min for x in self.__create_handles()])

    def year_max_min(self):
        """返回月度最大值中的最小值"""
        return min([x.max for x in self.__create_handles()])

    def year_min_max(self):
        """返回月度最小值中的最大值"""
        return max([x.min for x in self.__create_handles()])


def get_every_year_avg(area_dir):
    keys = []
    years = []
    year_avg = []
    growth_avg = []
    for a in os.listdir(area_dir):
        years.append(os.path.join(area_dir, a))
    for i in years:
        yd = YearData(i)
        # print(i[-4:])
        keys.append(i[-4: ])
        year_avg.append(yd.year_avg())
        growth_avg.append(yd.growth_time_avg())

    return {'year_avg': year_avg, 'growth_avg': growth_avg}


def get_max(area_dir):
    keys = []
    years = []
    year_max = []
    growth_max = []
    for a in os.listdir(area_dir):
        years.append(os.path.join(area_dir, a))
    for i in years:
        yd = YearData(i)
        # print(i[-4:])
        keys.append(i[-4: ])
        year_max.append(yd.year_max())
        growth_max.append(yd.growth_time_max())

    return {'year_max': year_max, 'growth_max': growth_max}


def get_min(area_dir):
    keys = []
    years = []
    year_min = []
    growth_min = []
    for a in os.listdir(area_dir):
        years.append(os.path.join(area_dir, a))
    for i in years:
        yd = YearData(i)
        # print(i[-4:])
        keys.append(i[-4: ])
        year_min.append(yd.year_min())
        growth_min.append(yd.growth_time_min())

    return {'year_min': year_min, 'growth_min': growth_min}

if __name__ == '__main__':
    # d = YearData(r"E:\毕设数据\QuNDVI_Excel\新洲区\Excel_2020")
    # print(d.year_avg())
    # print(d.growth_time_avg())
    # get_every_year_avg(r"E:\毕设数据\UsingTypeNDVI_Excel\2_林地")
    print(get_every_year_avg(r"E:\毕设数据\VegetationTypeNDVI_Excel\栽培"))

    # h = Handle(demo)
    # h.test()
